package org.auf.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.LinkedList;

import org.apache.log4j.Logger;

public class PointedDAOJDBC implements IPointedDAO {
	
	static Logger log = Logger.getLogger(UserDAOJDBC.class.getName());

	@Override
	public boolean deletePointed(Event event, User user) {
		int updates=0;
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection db = cm.checkOut();
		
		try{
			PreparedStatement st = db.prepareStatement("DELETE FROM tblpointed WHERE event=? AND user=?");
			st.setString(1, event.getId());
			st.setString(2, user.getId());
			updates =st.executeUpdate();
		
		}catch(Exception e){updates=-1;log.error("Error al generar la sentencia SQL y ejecutarla: "+e);}

		cm.checkIn(db);
		// TODO Auto-generated method stub
		return updates==1;
	}

	@Override
	public boolean insertPointed(Event event, User user) {
		int updates=0;
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection db = cm.checkOut();
		
		try{
			PreparedStatement st = db.prepareStatement("INSERT INTO tblpointed (event,user) values (?,?");
			st.setString(1, event.getId());
			st.setString(2, user.getId());
			updates =st.executeUpdate();
		
		}catch(Exception e){updates=-1;log.error("Error al generar la sentencia SQL y ejecutarla: "+e);}

		cm.checkIn(db);
		// TODO Auto-generated method stub
		return updates==1;
	}

	@Override
	public Collection<User> selectPointedByEvent(Event event) {
		Collection<User> sol = new LinkedList<User>();
		
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection db = cm.checkOut();
		
		try{
			PreparedStatement st = db.prepareStatement("SELECT * FROM tblpointed WHERE event=?");
			st.setString(1, event.getId());
			ResultSet rs = st.executeQuery();
		
			while (rs.next()){
				User user= new User();
				user=UserDAOJDBC.getInstance().selectUserByid(rs.getString("user"));
				sol.add(user);
			}
		
		}catch(Exception e){sol=null;log.error("Error al generar la sentencia SQL y ejecutarla: "+e);}

		cm.checkIn(db);
		// TODO Auto-generated method stub
		return sol;
	}

	@Override
	public Collection<Event> selectPointedByUser(User user) {
		Collection<Event> sol = new LinkedList<Event>();
		
		ConnectionManager cm = ConnectionManager.getInstance();
		Connection db = cm.checkOut();
		
		try{
			PreparedStatement st = db.prepareStatement("SELECT * FROM tblpointed WHERE user=?");
			st.setString(1, user.getId());
			ResultSet rs = st.executeQuery();
		
			while (rs.next()){
				Event event= new Event();
				event=EventDAOJDBC.getInstance().selectEvent(rs.getString("event"));
				sol.add(event);
			}
		
		}catch(Exception e){sol=null;log.error("Error al generar la sentencia SQL y ejecutarla: "+e);}

		cm.checkIn(db);
		// TODO Auto-generated method stub
		return sol;
	}

}
